//
//  HJInputBar.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJInputBar.h"
#import "TUIDefine.h"
#import "HJResponderTextView.h"
#import "NSString+emoji.h"
#import "TUIDefine.h"
#import "UIView+TUILayout.h"
#import "HJEmojiTextAttachment.h"
#import "HJRecordView.h"
#import <AVFAudio/AVFAudio.h>
#import "HJGradientButton.h"
#import "HJAlertController.h"
#import "NSString+QMUI.h"
#import <AVFoundation/AVFoundation.h>


@interface HJInputBar() <UITextViewDelegate, AVAudioRecorderDelegate, HJRecordViewDelegate>

@property (nonatomic, strong) HJRecordView *recordView;
@property (nonatomic, strong) NSDate *recordStartTime;
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) NSTimer *recordTimer;
@property (nonatomic, assign) BOOL isFocusOn;
@property (nonatomic, copy) NSString *voicePath;
@property (nonatomic, assign) NSInteger maximumTextLength;

@end

@implementation HJInputBar


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        [self setupViews];
        [self defaultLayout];
    }
    return self;
}

- (void)setupViews
{
    
    self.maximumTextLength = 2048;
    
    _lineView = [[UIView alloc] init];
    _lineView.backgroundColor = UIColor.tj_FFFFFFColor;
    
    _microphoneButton = [[UIButton alloc] init];
    [_microphoneButton addTarget:self action:@selector(clickVoiceBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_microphoneButton setImage:[UIImage imageNamed:@"input_bar_microphone"] forState:UIControlStateNormal];
    [self addSubview:_microphoneButton];
    
    _faceButton = [[UIButton alloc] init];
    [_faceButton addTarget:self action:@selector(clickFaceBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_faceButton setImage:[UIImage imageNamed:@"input_bar_face"] forState:UIControlStateNormal];
    [_faceButton setImage:[UIImage imageNamed:@"input_bar_face"] forState:UIControlStateSelected];

    [self addSubview:_faceButton];
    
    _keyboardButton = [[UIButton alloc] init];
    [_keyboardButton addTarget:self action:@selector(clickKeyboardBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_keyboardButton setImage:[UIImage imageNamed:@"input_bar_keyboard"] forState:UIControlStateNormal];
    _keyboardButton.hidden = YES;
    [self addSubview:_keyboardButton];
    
    _moreButton = [[UIButton alloc] init];
    [_moreButton addTarget:self action:@selector(clickMoreBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_moreButton setImage:[UIImage imageNamed:@"input_bar_more"] forState:UIControlStateNormal];
    [_moreButton setImage:[UIImage imageNamed:@"input_bar_more_select"] forState:UIControlStateSelected];
    _moreButton.backgroundColor = UIColor.whiteColor;


    [self addSubview:_moreButton];
    
    _sendButton = [[UIButton alloc] init];
    _sendButton.hidden = YES;
    [_sendButton addTarget:self action:@selector(clickSendBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_sendButton setImage:[UIImage imageNamed:@"input_bar_send_select"] forState:UIControlStateNormal];
    _sendButton.backgroundColor = UIColor.whiteColor;
    [self addSubview:_sendButton];
    
    _recordButton = [HJGradientButton buttonWithSuperView:self font:UIFontMake(14) color:UIColor.tj_333333Color title:nil];
    _recordButton.colors = @[
        UIColorMake(0xF4F3FA),
        UIColorMake(0xEFEDFB),
        UIColorMake(0xD1C9F4),
        UIColorMake(0xEBE7F9),
        UIColorMake(0xF3F2F7)
    ];
    [_recordButton addTarget:self action:@selector(didClickRecordButton) forControlEvents:UIControlEventTouchUpInside];
    [_recordButton setTitle:@"Click to record voice" forState:UIControlStateNormal];

    _recordButton.hidden = YES;
    _recordButton.addCornerRadius(10);
        
    _inputTextView = [[HJResponderTextView alloc] init];
    _inputTextView.delegate = self;
    _inputTextView.placeholder = @"Message";
   
    CGFloat topMargin = (TTextView_TextView_Height_Min - ceilf(UIFontMake(14).lineHeight)) * 0.5;
    _inputTextView.textContainerInset = UIEdgeInsetsMake(topMargin, 10, 10, 10);
    [_inputTextView setFont:UIFontMake(14)];
    _inputTextView.tintColor = UIColor.tj_cursorColor;
    _inputTextView.backgroundColor = UIColor.tj_F6F6F6Color;
    _inputTextView.textColor = UIColor.tj_333333Color;
    [_inputTextView setReturnKeyType:UIReturnKeySend];
    _inputTextView.addCornerRadius(10);
    [self addSubview:_inputTextView];
}

- (void)defaultLayout {
    _lineView.frame = CGRectMake(0, 0, Screen_Width, TLine_Heigh);
    CGSize buttonSize = TTextView_Button_Size;
    CGFloat buttonOriginY = (TTextView_Height - buttonSize.height) * 0.5;
    _microphoneButton.frame = CGRectMake(TTextView_Margin, buttonOriginY, buttonSize.width, buttonSize.height);
    _keyboardButton.frame = _microphoneButton.frame;
    
    _moreButton.frame = CGRectMake(Screen_Width - buttonSize.width - TTextView_Margin, buttonOriginY, buttonSize.width, buttonSize.height);
    _sendButton.frame = _moreButton.frame;
    _faceButton.frame = CGRectMake(_moreButton.frame.origin.x - buttonSize.width, buttonOriginY, buttonSize.width, buttonSize.height);
    
    CGFloat beginX = _microphoneButton.frame.origin.x + _microphoneButton.frame.size.width + TTextView_Margin;
    CGFloat endX = _faceButton.frame.origin.x - TTextView_Margin;
    
    _recordButton.frame = CGRectMake(beginX, (TTextView_Height - TTextView_TextView_Height_Min) * 0.5, endX - beginX, TTextView_TextView_Height_Min);
    _inputTextView.frame = _recordButton.frame;
    
   [self.placeholderLabel sizeToFit];
 
    _placeholderLabel.frame = CGRectMake(4, 10, self.placeholderLabel.tj_size.width, self.placeholderLabel.tj_size.height);
}

- (void)layoutButton:(CGFloat)height
{
    CGRect frame = self.frame;
    CGFloat offset = height - frame.size.height;
    frame.size.height = height;
    self.frame = frame;
    
    CGSize buttonSize = TTextView_Button_Size;
    CGFloat bottomMargin = (TTextView_Height - buttonSize.height) * 0.5;
    CGFloat originY = frame.size.height - buttonSize.height - bottomMargin;
    
    CGRect faceFrame = _faceButton.frame;
    faceFrame.origin.y = originY;
    _faceButton.frame = faceFrame;
    
    CGRect moreFrame = _moreButton.frame;
    moreFrame.origin.y = originY;
    _moreButton.frame = moreFrame;
    _sendButton.frame = moreFrame;
    
    CGRect voiceFrame = _microphoneButton.frame;
    voiceFrame.origin.y = originY;
    _microphoneButton.frame = voiceFrame;
    
    _keyboardButton.frame = _microphoneButton.frame;
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didChangeInputHeight:)]){
        [_delegate inputBar:self didChangeInputHeight:offset];
    }
}

- (void)clickVoiceBtn:(UIButton *)sender {
    if (_recordView.status == TJRecord_Status_Recording) {
        [HJHUD showMessage: @"In progress…"];
        return;
    }
    
    _recordButton.hidden = NO;
    _inputTextView.hidden = YES;
    _microphoneButton.hidden = YES;
    _keyboardButton.hidden = NO;
    _faceButton.hidden = NO;
    _moreButton.hidden = NO;
    [_inputTextView resignFirstResponder];
    [self layoutButton:TTextView_Height];
    
    NSLog(@"_keyboardButton = %@", _keyboardButton);
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchMore:)]){
        [_delegate inputBarDidTouchVoice:self];
    }
}

- (void)clickSendBtn:(UIButton *)sender {
    [self sendTextWithTextView:self.inputTextView];
}

- (void)clickKeyboardBtn:(UIButton *)sender {
    if (_recordView.status == TJRecord_Status_Recording) {
        [HJHUD showMessage:[_recordButton titleForState:UIControlStateSelected]];
        return;
    }
    
    _microphoneButton.hidden = NO;
    _keyboardButton.hidden = YES;
    _recordButton.hidden = YES;
    _inputTextView.hidden = NO;
    _faceButton.hidden = NO;
    _moreButton.hidden = NO;
    [self layoutButton:_inputTextView.frame.size.height + 2 * TTextView_Margin];
    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchKeyboard:)]){
        [_delegate inputBarDidTouchKeyboard:self];
    }
}

- (void)clickFaceBtn:(UIButton *)sender {
    if (_recordView.status == TJRecord_Status_Recording) {
        [HJHUD showMessage:[_recordButton titleForState:UIControlStateSelected]];
        return;
    }
    _microphoneButton.hidden = NO;
    _keyboardButton.hidden = YES;
    _recordButton.hidden = YES;
    _inputTextView.hidden = NO;
    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchFace:)]){
        [_delegate inputBarDidTouchFace:self];
    }
}

- (void)clickMoreBtn:(UIButton *)sender {
    if (_recordView.status == TJRecord_Status_Recording) {
        [HJHUD showMessage:[_recordButton titleForState:UIControlStateSelected]];
        return;
    }
        
    
    _recordButton.hidden = YES;
    _keyboardButton.hidden = YES;
    _inputTextView.hidden = NO;
    _microphoneButton.hidden = NO;
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchMore:)]){
        [_delegate inputBarDidTouchMore:self];
    }
}



- (void)didClickRecordButton
{
    if (_recordView.status == TJRecord_Status_Recording) {
        return;
    }
    
    AVAudioSessionRecordPermission permission = AVAudioSession.sharedInstance.recordPermission;
    /**
     * 新安装后第一次请求授权，需要再次判断是否为 Undetermined，避免出现错误
     * For the first request for authorization after a new installation, it is necessary to determine whether it is Undetermined again to avoid errors.
     */
    if (permission == AVAudioSessionRecordPermissionDenied || permission == AVAudioSessionRecordPermissionUndetermined) {
        [AVAudioSession.sharedInstance requestRecordPermission:^(BOOL granted) {
            if (!granted) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"Microphone permission is not enabled Go to settings to open microphone permissions" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"Go to system settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
                        [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
                    }
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];

                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.mm_viewController presentViewController:alert animated:YES completion:nil];
                });
            }
        }];
        return;
    }
    
    if(permission == AVAudioSessionRecordPermissionGranted){
        if (!_recordView) {
            _recordView = [[HJRecordView alloc] init];
            _recordView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - TabBarHeight);
        }
        [self.window addSubview:_recordView];
        _recordView.delegate = self;
        _recordStartTime = [NSDate date];
        [_recordView setStatus:TJRecord_Status_Recording];
        [_recordButton setTitle:@"In progress…" forState:UIControlStateNormal];
        [self showHapticFeedback];
        [self startRecord];
    }
}

//发送
- (void)didClickSend:(HJRecordView *)recordView {
    [recordView removeFromSuperview];
    [recordView reset];
    [_recordButton setTitle:@"Click to record voice" forState:UIControlStateNormal];
    _recordView.status = TJRecord_Status_TooLong;

    if (_voicePath) {
        if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendVoice:)]){
            [_delegate inputBar:self didSendVoice:_voicePath];
        }
    }
}

- (void)didClickCancel:(HJRecordView *)recordView {
    [self cancelRecord];
    _recordView.status = TJRecord_Status_Cancel;
    [recordView removeFromSuperview];
    [recordView reset];
    [_recordButton setTitle:@"Click to record voice" forState:UIControlStateNormal];
}

- (void)didClickMicrophone:(HJRecordView *)recordView {
    if (recordView.second <= 1) return;
    [self stopRecord];
    [recordView showOperationViews:YES];
}

- (void)showHapticFeedback{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle: UIImpactFeedbackStyleMedium];
        [generator prepare];
        [generator impactOccurred];
    });
}

- (void)showSendButton {
    self.sendButton.hidden = NO;
    self.moreButton.hidden = YES;
    self.inputTextView.placeholderLabel.alpha = 0;
}

- (void)hiddenSendButton {
    self.sendButton.hidden = YES;
    self.moreButton.hidden = NO;
    self.inputTextView.placeholderLabel.alpha = 1;
}
 
#pragma mark - talk

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.keyboardButton.hidden = YES;
    self.microphoneButton.hidden = NO;
    self.faceButton.hidden = NO;
    self.isFocusOn = YES;
    
    if (self.isFocusOn &&[textView.textStorage getPlainString].length > 0) {
        if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldBeginTyping:)]) {
            [_delegate inputTextViewShouldBeginTyping:textView];
        }
    }
    
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    self.isFocusOn = NO;
    if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldEndTyping:)]) {
        [_delegate inputTextViewShouldEndTyping:textView];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    
    if (textView.text.length) {
        [self showSendButton];
    } else {
        [self hiddenSendButton];
    }
    
    
    if (self.isFocusOn && [textView.textStorage getPlainString].length == 0) {
        if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldEndTyping:)]) {
            [_delegate inputTextViewShouldEndTyping:textView];
        }
    }
    CGSize size = [_inputTextView sizeThatFits:CGSizeMake(_inputTextView.frame.size.width, TTextView_TextView_Height_Max)];
    CGFloat oldHeight = _inputTextView.frame.size.height;
    CGFloat newHeight = size.height;
    
    if(newHeight > TTextView_TextView_Height_Max){
        newHeight = TTextView_TextView_Height_Max;
    }
    if(newHeight < TTextView_TextView_Height_Min){
        newHeight = TTextView_TextView_Height_Min;
    }
    if(oldHeight == newHeight){
        return;
    }
    
    __weak typeof(self) ws = self;
    [UIView animateWithDuration:0.25 animations:^{
        CGRect textFrame = ws.inputTextView.frame;
        textFrame.size.height += newHeight - oldHeight;
        ws.inputTextView.frame = textFrame;
        [ws layoutButton:newHeight + 2 * TTextView_Margin];
    }];
}

- (void)sendTextWithTextView:(UITextView *)textView {
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendText:)]) {
        NSString *sp = [[textView.textStorage getPlainString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (sp.length == 0) {
            [HJAlertController alertInController:self.mm_viewController title:nil message:@"Unable to send blank message" left:nil right:^(HJAlertAction * _Nonnull action) {
                action.title = @"OK";
                action.titleColor = UIColor.tj_mainColor;
            }];
        } else {
            [_delegate inputBar:self didSendText:[textView.textStorage getPlainString]];
            [self clearInput];
        }
    }
}
 
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //    if ([text containsString:@"["] && [text containsString:@"]"] ) {
    //        NSRange selectedRange = textView.selectedRange;
    //        if (selectedRange.length > 0) {
    //            [textView.textStorage deleteCharactersInRange:selectedRange];
    //        }
    //
    //        NSMutableAttributedString *textChange = [text getFormatEmojiStringWithFont:kTUIInputNoramlFont emojiLocations:nil];
    //        [textView.textStorage insertAttributedString:textChange atIndex:textView.textStorage.length];
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            self.inputTextView.selectedRange = NSMakeRange(self.inputTextView.textStorage.length + 1, 0);
    //        });
    //
    //        return NO;
    //    }
    
    if([text isEqualToString:@"\n"]){
        [self sendTextWithTextView:textView];
        return NO;
    }
    
    if (self.maximumTextLength < NSUIntegerMax) {
        
        // 如果是中文输入法正在输入拼音的过程中（markedTextRange 不为 nil），是不应该限制字数的（例如输入“huang”这5个字符，其实只是为了输入“黄”这一个字符），所以在 shouldChange 这里不会限制，而是放在 didChange 那里限制。
        if (textView.markedTextRange) {
            return YES;
        }
        
        BOOL isDeleting = range.length > 0 && text.length <= 0;
        if (isDeleting) {
            if (NSMaxRange(range) > textView.text.length) {
                // https://github.com/Tencent/QMUI_iOS/issues/377
                return NO;
            } else {
                return YES;
            }
        }
        
        NSUInteger rangeLength =  range.length;
        BOOL textWillOutofMaximumTextLength = textView.text.length - rangeLength + text.length > self.maximumTextLength;
        if (textWillOutofMaximumTextLength) {
            // 当输入的文本达到最大长度限制后，此时继续点击 return 按钮（相当于尝试插入“\n”），就会认为总文字长度已经超过最大长度限制，所以此次 return 按钮的点击被拦截，外界无法感知到有这个 return 事件发生，所以这里为这种情况做了特殊保护
            if (textView.text.length - rangeLength == self.maximumTextLength && [text isEqualToString:@"\n"]) {
                return NO;
            }
            // 将要插入的文字裁剪成多长，就可以让它插入了
            NSInteger substringLength = self.maximumTextLength - textView.text.length + rangeLength;
            
            if (substringLength > 0 && text.length > substringLength) {
                NSString *allowedText = [text qmui_substringAvoidBreakingUpCharacterSequencesWithRange:NSMakeRange(0, substringLength) lessValue:YES countingNonASCIICharacterAsTwo:NO];
                if (allowedText.length <= substringLength) {
                    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:allowedText];
                    textView.selectedRange = NSMakeRange(range.location + substringLength, 0);
                    
                    if ([textView.delegate respondsToSelector:@selector(textViewDidChange:)]) {
                        [textView.delegate textViewDidChange:textView];
                    }
                }
            }
            
                        
            if ([text isEqualToString:@""]) {
                
                if (textView.textStorage.length > range.location) {
                    // 一次性删除 @xxx 这种 @ 消息
                    // Delete the @ message like @xxx at one time
                    NSAttributedString *lastAttributedStr = [textView.textStorage attributedSubstringFromRange:NSMakeRange(range.location , 1)];
                    NSString *lastStr = [lastAttributedStr getPlainString];
                    
                    if ([textView.text characterAtIndex:range.location] == ']') {
                        NSUInteger location = range.location;
                        NSUInteger length = range.length;
                        int left = 91;     // '[' 对应的ascii码
                        int right = 93;    // ']' 对应的ascii码
                        while (location != 0) {
                            location --;
                            length ++ ;
                            int c = (int)[textView.text characterAtIndex:location];     // 将字符转换成ascii码，复制给int  避免越界
                            if (c == left) {
                                textView.text = [textView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
                                return NO;
                            }
                            else if (c == right) {
                                return YES;
                            }
                        }
                    }
                    
                    if (lastStr &&  lastStr.length>0 && [lastStr characterAtIndex:0] == ' ') {
                        NSUInteger location = range.location;
                        NSUInteger length = range.length;
                        
                        // '@' 对应的ascii码 '@'
                        // corresponds to ascii code
                        int at = 64;
                        // 空格(space) 对应的ascii码
                        // Space (space) corresponding ascii code
                        int space = 32;
                        
                        while (location != 0) {
                            location --;
                            length ++ ;
                            // 将字符转成ascii码，复制给int,避免越界
                            // Convert characters to ascii code, copy to int, avoid out of bounds
                            int c = (int)[[[textView.textStorage attributedSubstringFromRange:NSMakeRange(location, 1)] getPlainString] characterAtIndex:0];
                            
                            if (c == at) {
                                NSString *atText = [[textView.textStorage attributedSubstringFromRange:NSMakeRange(location, length)] getPlainString];
                                UIFont *textFont = kTUIInputNoramlFont;
                                NSAttributedString *spaceString = [[NSAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName: textFont}];
                                [textView.textStorage replaceCharactersInRange:NSMakeRange(location, length) withAttributedString:spaceString];
                                if (self.delegate && [self.delegate respondsToSelector:@selector(inputBar:didDeleteAt:)]) {
                                    [self.delegate inputBar:self didDeleteAt:atText];
                                }
                                return NO;
                            }
                            else if (c == space) {
                                // 避免出现 "@昵称 你好，很高兴认识 你(space)  "" 在空格后按del 过度删除到@
                                // Avoid "@nickname Hello, nice to meet you (space) "" Press del after a space to over-delete to @
                                break;
                            }
                        }
                    }
                    
                }
            }
            // 监听 @ 字符的输入，包含全角/半角
            // Monitor the input of @ character, including full-width/half-width
            else if ([text isEqualToString:@"@"] || [text isEqualToString:@"＠"]) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(inputBarDidInputAt:)]) {
                    [self.delegate inputBarDidInputAt:self];
                }
            }
            
            return NO;
        }
    }

    return YES;
}

- (void)onDeleteBackward:(HJResponderTextView *)textView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(inputBarDidDeleteBackward:)]) {
        [self.delegate inputBarDidDeleteBackward:self];
    }
}

- (void)clearInput
{
    [_inputTextView.textStorage deleteCharactersInRange:NSMakeRange(0, _inputTextView.textStorage.length)];
    [self textViewDidChange:_inputTextView];
}

- (NSString *)getInput
{
    return [_inputTextView.textStorage getPlainString];
}


- (void)addEmoji:(NSString *)emoji
{
    
    [_inputTextView setText:[_inputTextView.text stringByAppendingString:emoji]];
    if (!_inputTextView.markedTextRange) {
        if (_inputTextView.text.length > self.maximumTextLength) {
            _inputTextView.text = [_inputTextView.text qmui_substringAvoidBreakingUpCharacterSequencesWithRange:NSMakeRange(0, self.maximumTextLength) lessValue:YES countingNonASCIICharacterAsTwo:NO];
            return;
        }
    }
    
    if(_inputTextView.contentSize.height > TTextView_TextView_Height_Max){
        float offset = _inputTextView.contentSize.height - _inputTextView.frame.size.height;
        [_inputTextView scrollRectToVisible:CGRectMake(0, offset, _inputTextView.frame.size.width, _inputTextView.frame.size.height) animated:YES];
    }
    

    [self textViewDidChange:_inputTextView];
}
 

- (void)resetTextStyle {
    //After changing text selection, should reset style.
    NSRange wholeRange = NSMakeRange(0, _inputTextView.textStorage.length);
    
    [_inputTextView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
    [_inputTextView.textStorage removeAttribute:NSForegroundColorAttributeName range:wholeRange];
    [_inputTextView.textStorage addAttribute:NSForegroundColorAttributeName value:kTUIInputNormalTextColor range:wholeRange];
    [_inputTextView.textStorage addAttribute:NSFontAttributeName value:kTUIInputNoramlFont range:wholeRange];
}

- (void)backDelete {
    [self.inputTextView deleteBackward];
    [self textViewDidChange:_inputTextView];
}

- (void)updateTextViewFrame {
    [self textViewDidChange:[UITextView new]];
}

- (void)changeToKeyboard {
    [self clickKeyboardBtn:self.keyboardButton];
}

- (void)startRecord {
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    [session setActive:YES error:&error];
    
    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
                                   // 音频格式
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   //                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    
    NSString *path = [NSString stringWithFormat:@"%@_%ld_%@",[HJUserInfo userId], [[NSDate date] timestamp] , @"record.wav"].tj_tmpCachePath;
    NSURL *url = [NSURL fileURLWithPath:path];
    _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];
    _recorder.meteringEnabled = YES;
    [_recorder prepareToRecord];
    [_recorder record];
    [_recorder updateMeters];
    [_recordTimer invalidate];
    _recordTimer = nil;
    _recordTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(recordTick:) userInfo:nil repeats:YES];
}

- (void)recordTick:(NSTimer *)timer{
    [_recorder updateMeters];
    NSTimeInterval interval = _recorder.currentTime;
    if(interval + 0.15 >= 60){
        _recordView.second = 60;
        [_recordView stop];
        NSString *path = [self stopRecord];
        NSLog(@"path = %@", path);
        [_recordView showOperationViews:YES];
        [_recordView setStatus:TJRecord_Status_TooLong];
    } else {
        _recordView.second = interval;
    }
}


- (NSString *)stopRecord {
    if(_recordTimer){
        [_recordTimer invalidate];
        _recordTimer = nil;
    }
    if([_recorder isRecording]){
        [_recorder stop];
    }
    _voicePath = _recorder.url.path;
    
    
    NSURL *url = [NSURL fileURLWithPath:_voicePath];
    AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    long int duration = lroundf(CMTimeGetSeconds(audioAsset.duration));
    
    NSLog(@"duration = %ld, _recordView.second = %f", duration, _recordView.second);
    return _voicePath;
}

- (void)cancelRecord {
    if(_recordTimer){
        [_recordTimer invalidate];
        _recordTimer = nil;
    }
    if([_recorder isRecording]){
        [_recorder stop];
    }
    NSString *path = _recorder.url.path;
    if([[NSFileManager defaultManager] fileExistsAtPath:path]){
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
}

- (void)onThemeChanged {
    
}


//键盘的逻辑
//刚进来, 就是麦克风按钮, 发消息textView, 笑脸, 和更多按钮
//点击麦克风按钮,显示录音按钮,
//点击录音按钮就录音
//点击笑脸就出现笑脸就重置输入框变回发文字状态, 笑脸选中
//点击更多, 更多变成X, 重置输入框变回发文字状态

@end
